package com.yfve.eol.service;

import android.app.Service;
import android.car.Car;
import android.car.CarNotConnectedException;
import android.car.hardware.CarPropertyValue;
import android.car.hardware.CarYFDiagManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;

import com.yfve.eol.EolApplication;
import com.yfve.eol.EolHandler;

public class EolService extends Service {

    private static final String TAG = "EolService";
    private final CarYFDiagManager.CarVendorExtensionCallback mCarVendorExtensionCallback = new CarYFDiagManager.CarVendorExtensionCallback() {
        @Override
        public void onChangeEvent(CarPropertyValue carPropertyValue) {
            Log.i(TAG, "onChangeEvent: command = " + carPropertyValue.toString());
            Message msg = EolHandler.getEolHandler().obtainMessage();
            msg.what = EolHandler.MSG_EOL;
            msg.obj = carPropertyValue;
            EolHandler.getEolHandler().sendMessage(msg);
        }

        @Override
        public void onErrorEvent(int var1, int var2) {
            Log.e(TAG, "onErrorEvent: " + var1 + ", " + var1);
        }
    };
    private Car mCarApiClient;
    private CarYFDiagManager mCarYFDiagManager;

    @Override
    public void onCreate() {
        super.onCreate();
        connectCarService();
        Log.i(TAG, "onCreate: ");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void connectCarService() {
        mCarApiClient = Car.createCar(this, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.i(TAG, "Connect CarService success");
                try {
                    mCarYFDiagManager = (CarYFDiagManager) mCarApiClient.getCarManager(Car.VENDOR_YFDIAG_SERVICE);
                    mCarYFDiagManager.registerCallback(mCarVendorExtensionCallback);
                    EolApplication.setCarYFDiagManager(mCarYFDiagManager);
                    EolHandler.getEolHandler();
                } catch (CarNotConnectedException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.e(TAG, "onServiceDisconnected:");
            }
        });
        mCarApiClient.connect();
    }

    @Override
    public void onDestroy() {
        if (mCarApiClient != null) {
            mCarApiClient.disconnect();
            mCarApiClient = null;
            mCarYFDiagManager = null;
            EolApplication.setCarYFDiagManager(null);
        }
        super.onDestroy();
        Log.i(TAG, "onDestroy: disconnect CarService.");
    }

}
